#pragma once

#include <iostream>
#include <string>
#include <cstring>
#include "Calculate.hpp"

const static char *sep = "\r\n";
// len\r\nx op y\r\n
// 5\r\n1 + 1\r\n
class Protocol
{
public:
    void InCode()
    {

    }
    std::string DeCode(std::string &msg)
    {
        size_t s1_pos = msg.find(sep);
        if(s1_pos == std::string::npos) 
            return std::string();
        int len = std::stoi(msg.substr(0, s1_pos));
        size_t s2_pos = msg.find(sep, s1_pos + std::strlen(sep));
        if(s2_pos == std::string::npos)
            return std::string();    
        if(s2_pos - (s1_pos + std::strlen(sep)) != len)
            return std::string();
        std::string package = msg.substr(0, s2_pos + std::strlen(sep));
        msg.erase(0, s2_pos + std::strlen(sep));
        return package;
    }
    // std::string ReqSerialization(Calculate *cal)
    // {
    //     std::string body = std::to_string(cal->_x) + ' ' + cal->_op + ' ' + std::to_string(cal->_y);
    //     std::string package = std::to_string(body.size()) + sep + body + sep;
    //     return package;
    // }
    std::string ResSerialization(Calculate *cal)
    {
        std::string body = std::to_string(cal->_result) + ' ' + std::to_string(cal->_valid);
        std::string package = std::to_string(body.size()) + sep + body + sep;
        return package;
    }
    Calculate* ReqDeSerialization(std::string &package)
    {
        size_t pos = package.find(sep);
        int len = std::stoi(package.substr(0, pos));
        std::string body = package.substr(pos + std::strlen(sep), len);
        pos = body.find(' ');
        int x = std::stoi(body.substr(0, pos));
        pos = body.find(' ', pos + 1);
        char op = body[pos - 1];
        int y = std::stoi(body.substr(pos + 1));
        Calculate *cal = new Calculate(x, y, op);
        return cal;
    }
    // void ResDeSerialization()
    // {

    // }
private:

};